package com.mikgonz.farkle;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.view.View;

import com.markupartist.android.widget.ActionBar.Action;

@SuppressWarnings("rawtypes")
public class ReflectionAction implements Action {

	private int drawableId;

	private Class[] args;
	private String methodName;
	private Class activityClass;
	private Object activityInstance;
	private Object[] params;

	public ReflectionAction(int drawableId, Class[] args, String methodName,
			Class activityClass, Object activityInstance, Object[] params) {
		super();
		this.drawableId = drawableId;
		this.args = args;
		this.methodName = methodName;
		this.activityClass = activityClass;
		this.activityInstance = activityInstance;
		this.params = params;
	}

	@Override
	public int getDrawable() {
		return drawableId;
	}

	@Override
	public void performAction(View view) {
		Method m = getMethod();
		invokeMethod(m);

	}

	private void invokeMethod(Method m) {

		try {
			m.invoke(activityInstance, params);
		} catch (IllegalArgumentException e) {

			e.printStackTrace();
		} catch (IllegalAccessException e) {

			e.printStackTrace();
		} catch (InvocationTargetException e) {

			e.printStackTrace();
		}

	}

	private Method getMethod() {
		Method m = null;

		try {
			m = activityClass.getMethod(methodName, args);
		} catch (SecurityException e) {

			e.printStackTrace();
		} catch (NoSuchMethodException e) {

			e.printStackTrace();
		}

		return m;
	}

}
